<template>
  <div class="app-container" v-if="commodityForm.mallSpuConfig">
    <el-form :model="commodityForm" :rules="rules" label-width="80px" ref="commodityFormDom">
      <div class="" v-show="pageType == 1">
        <h1>商品基本信息</h1>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="commodityForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="
            commodityForm.columnType == 1 ||
            commodityForm.columnType == 2 ||
            commodityForm.columnType == 4
          ">
            <el-form-item label="赠送金积分数量" prop="sendJinjifenNum" label-width="140">
              <el-input v-model="commodityForm.sendJinjifenNum" placeholder="请输入赠送金积分数量" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="
            commodityForm.columnType == 1 ||
            commodityForm.columnType == 2 ||
            commodityForm.columnType == 4
          ">
            <el-form-item label="是否只可现金支付" prop="cashPay" label-width="140">
              <el-select v-model="commodityForm.cashPay">
                <el-option v-for="item in cashPayList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="
            commodityForm.columnType == 1 ||
            commodityForm.columnType == 2 ||
            commodityForm.columnType == 4
          ">
            <el-form-item label="余额和现金支付时余额支付比例" prop="balanceRate" label-width="220" type="number" :min="0" :max="1">
              <el-input-number v-model="commodityForm.balanceRate" :precision="2" :step="0.01" :max="0.99"
                :min="0.01" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="
            commodityForm.columnType == 13
          ">
            <el-form-item label="熵豆可使用数量" prop="xiaofeijinPrice" label-width="140">
              <el-input type="number" v-model="commodityForm.xiaofeijinPrice" placeholder="请输入商品原价" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="commodityForm.columnType == 3 || commodityForm.columnType == 5">
            <el-form-item label="让利比例" prop="di-scountRate" label-width="140">
              <el-input-number v-model="commodityForm.discountRate" :max="100" :min="1" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6" v-if="commodityForm.columnType == 6">
            <el-form-item label="支付方式" prop="payType" label-width="140">
              <el-select v-model="commodityForm.payType" placeholder="请选择支付方式">
                <el-option v-for="item in payTypeArr" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="商品现价" prop="price">
              <el-input type="number" v-model="commodityForm.price" placeholder="请输入商品现价" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="排序" prop="orderBy">
              <el-input type="number" v-model="commodityForm.orderBy" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="新品飙升榜" prop="chartOneOrderBy" label-width="90px">
              <el-input type="number" v-model="commodityForm.chartOneOrderBy" placeholder="请输入新品飙升榜" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品质好评榜" prop="chartTwoOrderBy" label-width="90px">
              <el-input type="number" v-model="commodityForm.chartTwoOrderBy" placeholder="请输入新品飙升榜" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="所属专区" prop="columnType">
              <el-select v-model="commodityForm.columnType" placeholder="请选择所属专区">
                <el-option v-for="item in columnTypeArr" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销量" prop="salesVolume">
              <el-input type="number" v-model="commodityForm.salesVolume" placeholder="请输入销量" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属分类" prop="type" v-if="commodityForm.columnType != 13">
              <el-select v-model="commodityForm.type" placeholder="请选择所属分类">
                <el-option v-for="item in classification" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属分类" prop="type" v-if="commodityForm.columnType == 13">
              <el-select v-model="commodityForm.type" placeholder="请选择所属分类">
                <el-option v-for="item in zichanTypeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="折扣套票" prop="zhekouArr">
              <el-select v-model="commodityForm.zhekoutaopiaoType" placeholder="请选择">
                <el-option v-for="item in zhekouArr" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" v-if="commodityForm.columnType == 5">
            <el-form-item label="孵化分类" prop="preType">
              <el-select v-model="commodityForm.preType" placeholder="请选择孵化分类">
                <el-option v-for="item in preTypeArr" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="6" v-if="commodityForm.columnType == 5">
            <el-form-item label="赠送多少元熵豆" prop="sendShangdouPrice" label-width="140">
              <el-input type="number" v-model="commodityForm.sendShangdouPrice" placeholder="请输入赠送多少元熵豆" />
            </el-form-item>
          </el-col> -->

          <el-col :span="6" v-if="commodityForm.columnType == 8">
            <el-form-item label="数字馆一级分类" prop="mathTypeOne" label-width="140">
              <el-select v-model="commodityForm.mathTypeOne" placeholder="请选择" @change="getMathTypeTwoArr">
                <el-option v-for="item in mathTypeOneArr" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" v-if="commodityForm.columnType == 8">
            <el-form-item label="数字馆二级分类" prop="mathTypeTwo" label-width="140">
              <el-select v-model="commodityForm.mathTypeTwo" placeholder="请选择">
                <el-option v-for="item in mathTypeTwoArr" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="商品封面图" prop="cover" label-width="100">
            <ImageCropUpload v-model="commodityForm.cover"></ImageCropUpload>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="商品详情banner" prop="icons" label-width="100">
            <ImageUpload v-model="commodityForm.icons"></ImageUpload>
          </el-form-item>
        </el-row>

        <!-- <el-row :gutter="10">
                    <el-col :span="4">
                        <el-form-item label="是否支持货币支付" prop="mallSpuConfig.moneyPay" label-width="130">
                            <el-radio-group v-model="commodityForm.mallSpuConfig.moneyPay">
                                <el-radio :label="0">否</el-radio>
                                <el-radio :label="1">是</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <div v-if="commodityForm.mallSpuConfig.moneyPay == 1">
                        <el-button type="primary" @click="addMoneyPay">新增</el-button>
                    </div>
                </el-row> -->

        <div class="" v-if="commodityForm.mallSpuConfig.moneyPay == 1">
          <div class="mb-16" v-for="(item, index) in commodityForm.mallSpuConfig
            ?.mallSpuMoneyPays" :key="index">
            <el-row :gutter="10">
              <el-col :span="3">
                <el-select v-model="item.moneyId" class="" placeholder="选择货币">
                  <el-option v-for="item in currency" :key="item.id" :label="item.moneyName" :value="item.id"
                    :disabled="item.disabled" />
                </el-select>
              </el-col>
              <el-col :span="3">
                <el-input type="number" v-model="item.rate" placeholder="请输入比例" />
              </el-col>
              <el-button type="danger" @click="deletePays(index)">删除</el-button>
            </el-row>
          </div>
        </div>

        <!-- <el-row :gutter="10">
                    <el-col :span="5">
                        <el-form-item label="是否支持现金货币支付" prop="mallSpuConfig.cashMoneyPay" label-width="160">
                            <el-radio-group v-model="commodityForm.mallSpuConfig.cashMoneyPay">
                                <el-radio :label="0">否</el-radio>
                                <el-radio :label="1">是</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <div v-if="commodityForm.mallSpuConfig.cashMoneyPay == 1">
                        <el-button type="primary" @click="addCashMoneyPay">新增</el-button>
                    </div>
                </el-row> -->

        <div class="" v-if="commodityForm.mallSpuConfig.cashMoneyPay == 1">
          <div class="mb-16" v-for="(item, index) in commodityForm.mallSpuConfig
            ?.mallSpuCashMoneyPays" :key="index">
            <el-row :gutter="10">
              <el-col :span="3">
                <el-select v-model="item.moneyId" class="" placeholder="选择货币">
                  <el-option v-for="item in spuCashMoneyList" :key="item.id" :label="item.moneyName" :value="item.id"
                    :disabled="item.disabled" />
                </el-select>
              </el-col>
              <el-col :span="3">
                <el-input type="number" v-model="item.rate" placeholder="请输入比例" />
              </el-col>
              <el-button type="danger" @click="deletecashMoneyPay(index)">删除</el-button>
            </el-row>
          </div>
        </div>

        <el-row :gutter="10" v-if="commodityForm.columnType == 2">
          <el-col :span="4">
            <el-form-item label="选择抵扣券" prop="mallSpuConfig.sendMoney" label-width="100">
              <el-button type="primary" @click="addSendMoney">新增</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="">
          <div class="mb-16" v-for="(item, index) in commodityForm.mallSpuVoucherList" :key="index">
            <el-row :gutter="10">
              <el-col :span="3">
                <el-select v-model="item.voucherId" placeholder="搜索选择抵扣券" filterable remote
                  :remote-method="getCurrency">
                  <el-option v-for="item in currencySendList" :key="item.id" :label="item.name" :value="item.id"
                    :disabled="item.disabled" />
                </el-select>
              </el-col>
              <el-col :span="3">
                <el-input type="number" v-model="item.num" placeholder="请输入数量" />
              </el-col>
              <el-button type="danger" @click="deleteSend(index)">删除</el-button>
            </el-row>
          </div>
        </div>

        <el-form-item label="商品详情" prop="detail" label-width="100">
          <vue-ueditor-wrap v-model="commodityForm.detail" :config="ueditorConfig"></vue-ueditor-wrap>
        </el-form-item>
      </div>

      <div class="" v-if="pageType == 2">
        <h1>商品规格</h1>
        <el-button type="primary" @click="addSpecification">添加规格</el-button>

        <div class="specification_wrap specValue" v-for="(item, index) in commercialSpecification" :key="index">
          <div class="">
            <div class="mb-32">
              商品属性:
              <el-select v-model="item.specId" placeholder="请选择商品属性" @change="specificationChange(item)">
                <el-option v-for="item in specificationList" :key="item.id" :label="item.name" :value="item.id"
                  :disabled="item.disabled" />
              </el-select>
            </div>

            <div class="specValue">
              商品规格:
              <el-tag v-for="(i, j) in item.specValue" :key="j" closable @close="handleClose(item.specValue, j)">
                {{ i }}
              </el-tag>

              <el-button :icon="Plus" @click="addspecValue(index)" v-if="item.tempIsSpec"
                style="width: 120px; margin-left: 16px">添加</el-button>

              <el-input placeholder="请添加规格值" v-model="tempSpecValue" v-else style="width: 120px; margin-left: 16px"
                @keyup.enter="confirmSpec(index)" @blur="confirmSpec(index)" />
            </div>
          </div>
          <el-button type="danger" @click="deleteSpec(index)">删除属性</el-button>
        </div>

        <div class="" v-if="productsSkus.length > 0">
          <p style="margin: 24px 0 10px 0">
            价格 / 库存(<span style="color: #999">请一次性规划好表格内容后再填写表格数据</span>)
          </p>

          <el-table :data="productsSkus" style="width: 100%">
            <el-table-column align="center" v-for="(item, index) in productsSkus[0].mallSkuSpecs" :key="index">
              <template #header>
                {{ item.specName }}
              </template>
              <template #default="scope">
                {{
                  scope.row.mallSkuSpecs[0].specName == item.specName
                    ? scope.row.mallSkuSpecs[0].specValue
                    : scope.row.mallSkuSpecs[1].specValue
                }}
              </template>
            </el-table-column>

            <el-table-column label="价格（元）" width="300" align="center">
              <template #default="scope">
                <div style="display: flex; flex-wrap: wrap">
                  <div style="display: flex; align-items: center" v-if="
                    commodityForm.columnType == 1 ||
                    commodityForm.columnType == 2 ||
                    commodityForm.columnType == 4
                  ">
                    <span>赠送金积分数量</span>
                    <el-input-number v-model="scope.row.sendJinjifenNum" :min="0" label="赠送金积分数量">
                    </el-input-number>
                  </div>
                  <div style="display: flex; align-items: center" v-if="
                    commodityForm.columnType == 13
                  ">
                    <span>熵豆可使用数量</span>
                    <el-input-number v-model="scope.row.xiaofeijinPrice" :min="0" label="消费金可使用数量">
                    </el-input-number>
                  </div>
                  <!-- <div style="display: flex; align-items: center" v-if="
                    commodityForm.columnType == 5
                  ">
                    <span>赠送多少元熵豆</span>
                    <el-input-number v-model="scope.row.sendShangdouPrice" :min="0" label="赠送多少元熵豆">
                    </el-input-number>
                  </div> -->
                  <div style="display: flex; margin-top: 20px">
                    <span style="margin: 0 20px">现价</span>
                    <el-input-number v-model="scope.row.price" :min="0" label="价格">
                    </el-input-number>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="预览图" width="155" align="center">
              <template #default="scope">
                <ImageUpload :limit="1" v-model="scope.row.icons" style="width: 148px; height: 148px">
                </ImageUpload>
              </template>
            </el-table-column>

            <el-table-column label="库存">
              <template #default="scope">
                <el-input type="number" v-model.number="scope.row.stock" :min="0"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-form>

    <div class="footer">
      <el-button type="primary" @click="pageType == 1 ? (pageType = 2) : (pageType = 1)">{{ pageType == 1 ? "下一步" :
        "上一步"
        }}</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script setup name="CommodityAdd">
import { reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { childrenByCode } from "@/api/system/type";
import { listMoney } from "@/api/money/money";
import { innerList } from "@/api/mall/mallSpec";
import {
  addMallSpu,
  updateMallSpu,
  getMallSpu,
  innerListMallSpu,
} from "@/api/mall/mallSpu";
import { Plus } from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const currency = ref([]);
const currencySendList = ref([]);
const zichanTypeList = ref([]);

function getCurrency(name) {
  innerListMallSpu({
    name,
    columnType: 12,
  }).then((res) => {
    currencySendList.value = res.data;
  });
}

getCurrency("");

const spuCashMoneyList = ref([]);
const giveTypeList = ref([
  {
    label: "赠送数量",
    value: 0,
  },
  {
    label: "赠送比例",
    value: 1,
  },
]);
const ueditorConfig = ref({
  // 编辑器不自动被内容撑高
  autoHeightEnabled: true,
  // 初始容器高度
  initialFrameHeight: 400,
  // 初始容器宽度
  initialFrameWidth: "100%",
  UEDITOR_HOME_URL: "/ueditor/",
});
const pageType = ref(1);
const specificationList = ref([]);
const preTypeArr = ref([]);

async function getPreType() {
  const res = await childrenByCode({
    code: "FUHUA",
  });
  preTypeArr.value = res.data;
}

getPreType();

const mathTypeOneArr = ref([]);
const mathTypeTwoArr = ref([]);

async function getMathType() {
  const res = await childrenByCode({
    code: "SHUZIGUAN",
  });
  mathTypeOneArr.value = res.data;
}

getMathType();

async function getMathTypeTwoArr(e) {
  commodityForm.value.mathTypeTwo = "";
  let index = mathTypeOneArr.value.findIndex(
    (item) => item.id == commodityForm.value.mathTypeOne
  );
  if (index == -1) {
    return;
  }
  const res = await childrenByCode({
    code: mathTypeOneArr.value[index].code,
  });
  mathTypeTwoArr.value = res.data;
}

const commercialSpecification = ref([]);
const tempSpecValue = ref("");
const tempSpecIndex = ref(0);
const productsSkus = ref([]);
const classification = ref([]);
const zhekouArr = ref([]);
const payTypeArr = ref([
  {
    label: "金积分",
    value: 1,
  },
  {
    label: "功德金",
    value: 2,
  },
]);

const columnTypeArr = ref([
  {
    label: "金积分达人",
    value: 1,
  },
  {
    label: "社群达人",
    value: 2,
  },
  {
    label: "本地生活",
    value: 3,
  },
  {
    label: "创业合伙人",
    value: 4,
  },
  {
    label: "消费增值区",
    value: 5,
  },
  {
    label: "熵豆兑换专区",
    value: 6,
  },
  {
    label: "创业联盟区",
    value: 7,
  },
  {
    label: "跨国商贸",
    value: 8,
  },
  {
    label: "社区数字店",
    value: 10,
  },
  {
    label: "趣味消费节",
    value: 11,
  },
  {
    label: "商品折扣券",
    value: 12,
  },
  {
    label: "资产包",
    value: 13,
  },
]);

const storeId = ref(null);

const data = reactive({
  commodityForm: {},
  rules: {
    discountRate: [
      {
        required: true,
        message: "请输入让利比例",
        trigger: "blur",
      },
    ],
    name: [
      {
        required: true,
        message: "请输入商品名称",
        trigger: "blur",
      },
    ],
    mathTypeOne: [
      {
        required: true,
        message: "请选择数字馆一级分类",
        trigger: "change",
      },
    ],
    payType: [
      {
        required: true,
        message: "请选择支付方式",
        trigger: "change",
      },
    ],
    columnType: [
      {
        required: true,
        message: "请选择所属专区",
        trigger: "change",
      },
    ],
    price: [
      {
        required: true,
        message: "请输入商品现价",
        trigger: "blur",
      },
    ],
    cover: [
      {
        required: true,
        message: "请上传商品封面图",
        trigger: "change",
      },
    ],
    icons: [
      {
        required: true,
        message: "请上传商品封面图",
        trigger: "change",
      },
    ],
    detail: [
      {
        required: true,
        message: "请填写商品详情",
        trigger: "change",
      },
    ],
  },
});

const cashPayList = ref([
  {
    label: "是",
    value: 1,
  },
  {
    label: "否",
    value: 0,
  },
]);

const { commodityForm, rules } = toRefs(data);

// 抵扣券
const mallSpuSendsObj = ref({
  voucherId: "", //货币id
  num: "", //赠送的数量/比例
});

// 货币支付定义
const mallSpuMoneyPays = ref({
  moneyId: "", //货币id
  rate: "", //支付比例
});

onMounted(() => {
  route.query.storeId && (storeId.value = route.query.storeId);

  getCommodityType();
  reset();
});

function reset() {
  if (route.query?.id) {
    getMallSpu(route.query?.id).then((res) => {
      productsSkus.value = res.data.mallSkus;
      commodityForm.value = {
        ...res.data,
        mallSpuVoucherList: res.data.mallSpuVoucherList
          ? res.data.mallSpuVoucherList
          : [],
      };
      console.log(commodityForm.value);
    });
  } else {
    commodityForm.value = {
      id: null,
      name: null, //商品名称
      columnType: null, //商品所属专区
      brand: null, //商品品牌
      xiaofeijinPrice: null, //消费金可使用数量
      price: null, //商品现价
      orderBy: null, //排序
      isHot: 0, //是否推荐
      cover: null, //商品封面图
      icons: null, //商品轮播图，
      detail: "", //商品详情
      mallSpuConfig: {
        moneyPay: 0, // 是否支持货币支付0否1是
        sendMoney: 0, //是否赠送货币
        mallSpuSends: [], //赠送货币的详细信息
        mallSpuMoneyPays: [], //货币支付可以有多种
        cashMoneyPay: 0, //是否支持现金货币支付
        mallSpuCashMoneyPays: [],
      },
      mallSkus: [],
      salesVolume: null,
      discountRate: null,
      preType: null,
      mathTypeOne: null,
      mathTypeTwo: null,
      cashPay: null,
      chartTwoOrderBy: null,
      chartOneOrderBy: null,
      balanceRate: null,
      groupBuy: route.query?.groupBuy,
      mallSpuVoucherList: [],
      sendJinjifenNum: null,
      sendShangdouPrice: null
    };
    route.query.columnType &&
      (commodityForm.value.columnType = Number(route.query.columnType));
    proxy.resetForm("commodityFormDom");
  }
}

const getCommodityType = async () => {
  const res = await childrenByCode({
    code: "classification",
  });
  console.log(res, "商品分类");
  classification.value = res.data;

  const zhichanType = await childrenByCode({
    code: "zichanbao_type",
  });

  zichanTypeList.value = zhichanType.data;

  const res2 = await childrenByCode({
    code: "zhekoutaopiaoqu",
  });
  console.log(res2, "折扣");
  zhekouArr.value = res2.data;

  const res4 = await listMoney();
  console.log(res4, "货币");
  currency.value = res4.rows;

  spuCashMoneyList.value = JSON.parse(JSON.stringify(res4.rows));
};

/**
 * 新增货币
 */
const addMoneyPay = () => {
  commodityForm.value.mallSpuConfig.mallSpuMoneyPays.push(
    JSON.parse(JSON.stringify(mallSpuMoneyPays.value))
  );
};

// 删除货币 是否支持现金货币支付
const deletecashMoneyPay = (index) => {
  commodityForm.value.mallSpuConfig.mallSpuCashMoneyPays.splice(index, 1);
};

/**
 * 新增货币 是否支持现金货币支付
 */
const addCashMoneyPay = () => {
  commodityForm.value.mallSpuConfig.mallSpuCashMoneyPays.push(
    JSON.parse(JSON.stringify(mallSpuMoneyPays.value))
  );
};

// 删除货币
const deletePays = (index) => {
  commodityForm.value.mallSpuConfig.mallSpuMoneyPays.splice(index, 1);
};

// 监听已有货币 有则选择禁用
// watch(
//   () => commodityForm.value.mallSpuConfig?.mallSpuMoneyPays,
//   (newVal) => {
//     for (let i = 0; i < currency.value.length; i++) {
//       const Index = newVal.findIndex((item) => {
//         return item.moneyId === currency.value[i].id;
//       });
//       if (Index != -1) {
//         currency.value[i].disabled = true;
//       } else {
//         currency.value[i].disabled = false;
//       }
//     }
//   },
//   { deep: true }
// );

// 监听已有货币 有则选择禁用
// watch(
//   () => commodityForm.value.mallSpuConfig?.mallSpuCashMoneyPays,
//   (newVal) => {
//     for (let i = 0; i < spuCashMoneyList.value.length; i++) {
//       const Index = newVal.findIndex((item) => {
//         return item.moneyId === spuCashMoneyList.value[i].id;
//       });
//       if (Index != -1) {
//         spuCashMoneyList.value[i].disabled = true;
//       } else {
//         spuCashMoneyList.value[i].disabled = false;
//       }
//     }
//   },
//   { deep: true }
// );

// 新增赠送
const addSendMoney = () => {
  commodityForm.value.mallSpuVoucherList.push(
    JSON.parse(JSON.stringify(mallSpuSendsObj.value))
  );
};

// 删除赠送
const deleteSend = (index) => {
  commodityForm.value.mallSpuVoucherList.splice(index, 1);
};

// 监听已有货币 有则选择禁用
watch(
  () => commodityForm.value?.mallSpuVoucherList,
  (newVal) => {
    if (commodityForm.value?.mallSpuVoucherList) {
      console.log(newVal, "newVal");
      for (let i = 0; i < currencySendList.value.length; i++) {
        const Index = newVal.findIndex((item) => {
          return item.voucherId === currencySendList.value[i].id;
        });
        if (Index != -1) {
          currencySendList.value[i].disabled = true;
        } else {
          currencySendList.value[i].disabled = false;
        }
      }
    }
  },
  { deep: true }
);

const remoteMethod = async (e) => {
  const res = await innerList({
    name: e,
  });
  specificationList.value = res.data;
};
remoteMethod("");

// 添加规格
const addSpecification = () => {
  if (commercialSpecification.value.length > 1) {
    proxy.$modal.msg("最多添加俩种商品属性!");
  } else {
    commercialSpecification.value.push({
      specId: "",
      specName: "",
      specValue: [],
      tempIsSpec: true,
    });
  }
  calculateProductsSkus();
};

const specificationChange = (item) => {
  specificationList.value.forEach((i) => {
    if (item.specId == i.id) {
      item.specName = i.name;
    }
  });
};

// 添加规格值
const addspecValue = (index) => {
  tempSpecIndex.value = index;
  tempSpecValue.value = "";
  commercialSpecification.value[index].tempIsSpec = false;
};

const confirmSpec = (index) => {
  commercialSpecification.value[index].specValue.push(tempSpecValue.value);
  commercialSpecification.value[index].tempIsSpec = true;
  calculateProductsSkus();
};

const handleClose = (item, index) => {
  item.splice(index, 1);
  calculateProductsSkus();
};

const deleteSpec = (index) => {
  commercialSpecification.value.splice(index, 1);
  calculateProductsSkus();
};

// 判断选过的商品属性不能再选
// watch(
//   () => commercialSpecification.value,
//   (newVal) => {
//     for (let i = 0; i < specificationList.value.length; i++) {
//       const Index = newVal.findIndex((item) => {
//         return item.specId === specificationList.value[i].id;
//       });
//       if (Index != -1) {
//         specificationList.value[i].disabled = true;
//       } else {
//         specificationList.value[i].disabled = false;
//       }
//     }
//   },
//   { deep: true }
// );

// 计算productsSkus
const calculateProductsSkus = () => {
  // 判断commercialSpecification是否为空,为空则productsSkus空
  if (commercialSpecification.value.length == 0) {
    productsSkus.value = [];
    return;
  }

  // 循环商品规格数组
  for (let i = 0; i < commercialSpecification.value.length; i++) {
    if (commercialSpecification.value[i].specId == "") {
      productsSkus.value = [];
      return;
    }
    // 循环内部规格值数组 如果规格值数组为空则productsSkus空
    if (commercialSpecification.value[i].specValue.length == 0) {
      productsSkus.value = [];
      return;
    }
  }

  productsSkus.value = [];

  // 如果有值则开始计算productsSkus的值
  // 判断商品规格数组长度 如果等于1 则只需走一层循环
  if (commercialSpecification.value.length == 1) {
    commercialSpecification.value[0].specValue.forEach((i, j) => {
      productsSkus.value.push({
        id: j + 1,
        xiaofeijinPrice: 0, //原价
        sendJinjifenNum: 0, //原价
        sendShangdouPrice: 0,
        price: 0, //现价
        icons: "", //图片
        stock: 0, //库存
        mallSkuSpecs: [
          //分类 + 规格 数组  一个分类对应多个规格值多个商品信息
          {
            specId: commercialSpecification.value[0].specId, //商品规格id
            specName: commercialSpecification.value[0].specName, //为了页面展示需要规格类型名
            specValue: i, //商品规格值
          },
        ],
      });
    });
  }

  // 判断商品规格数组长度 如果等于2 则只需走俩层循环
  if (commercialSpecification.value.length == 2) {
    commercialSpecification.value[0].specValue.forEach((i, j) => {
      commercialSpecification.value[1].specValue.forEach((item, index) => {
        productsSkus.value.push({
          id: j + 1,
          xiaofeijinPrice: 0, //原价
          sendJinjifenNum: 0, //原价
          price: 0, //现价
          icons: "", //图片
          stock: 0, //库存
          mallSkuSpecs: [
            //分类 + 规格 数组  一个分类对应多个规格值多个商品信息
            {
              specId: commercialSpecification.value[0].specId, //商品规格id
              specName: commercialSpecification.value[0].specName, //为了页面展示需要规格类型名
              specValue: i, //商品规格值
            },
            {
              specId: commercialSpecification.value[1].specId, //商品规格id
              specName: commercialSpecification.value[1].specName, //为了页面展示需要规格类型名
              specValue: item, //商品规格值
            },
          ],
        });
      });
    });
  }
};

const cancel = () => {
  router.go(-1);
};

const submitForm = () => {
  // 判断支付货币
  // if (commodityForm.value.mallSpuConfig?.moneyPay == 1) {
  //     if (commodityForm.value.mallSpuConfig.mallSpuMoneyPays.length == 0) {
  //         proxy.$modal.msg('请正确填写货币支付信息!')
  //         return
  //     } else {
  //         const moneyId = commodityForm.value.mallSpuConfig.mallSpuMoneyPays.some((obj) => obj.moneyId === "")
  //         const rate = commodityForm.value.mallSpuConfig.mallSpuMoneyPays.some((obj) => obj.rate === "")
  //         if (moneyId || rate) {
  //             proxy.$modal.msg('请正确填写货币支付信息!')
  //             return
  //         }
  //     }
  // }
  // 判断赠送货币
  // if (commodityForm.value.mallSpuConfig.sendMoney == 1) {
  //     if (commodityForm.value.mallSpuConfig.mallSpuSends.length == 0) {
  //         proxy.$modal.msg('请正确填赠送信息!')
  //         return
  //     } else {
  //         const moneyId = commodityForm.value.mallSpuConfig.mallSpuSends.some((obj) => obj.moneyId === "")
  //         const rate = commodityForm.value.mallSpuConfig.mallSpuSends.some((obj) => obj.rate === "")
  //         if (moneyId || rate) {
  //             proxy.$modal.msg('请正确填写赠送信息!')
  //             return
  //         }
  //     }
  // }

  // 判断商品规格
  if (productsSkus.value.length == 0) {
    proxy.$modal.msg("请添加商品规格!");
    return;
  }
  try {
    productsSkus.value.forEach((item) => {
      if (!item.price) {
        throw new Error("价格未填写！");
      }
      if (!item.stock) {
        throw new Error("库存没有加！");
      }
      if (!item.icons) {
        throw new Error("图片未上传！");
      }
    });

    commodityForm.value.mallSkus = productsSkus.value;
  } catch (e) {
    proxy.$modal.msg(e.message);
    return;
  }

  proxy.$refs["commodityFormDom"].validate((valid) => {
    if (valid) {
      if (commodityForm.value.id) {
        delete commodityForm.value.verifyBy;
        delete commodityForm.value.verifyRemark;
        delete commodityForm.value.verifyState;
        delete commodityForm.value.verifyTime;
        updateMallSpu({
          ...commodityForm.value,
        }).then((res) => {
          console.log(res, "修改商品");
          proxy.$modal.msgSuccess("修改商品");
          cancel();
        });
      } else {
        let apiForm = {
          ...commodityForm.value,
          storeId: storeId.value,
        };
        if (storeId.value == null) {
          delete apiForm.storeId;
        }
        addMallSpu(apiForm).then((res) => {
          proxy.$modal.msgSuccess("添加成功");
          cancel();
        });
      }
    } else {
      proxy.$modal.msg("请完整填写必填信息!");
    }
  });
};
</script>

<style lang="scss" scoped>
.mb-16 {
  margin-bottom: 16px;
}

.mb-32 {
  margin-bottom: 32px;
}

.footer {
  text-align: center;
  margin-top: 50px;
}

.specification_wrap {
  padding: 32px;
  border: 1px solid #e5e5e5;
  background: #fcfcfc;
  margin-top: 16px;
  border-radius: 4px;
  justify-content: space-between;
}

.specValue {
  display: flex;
  align-items: center;
}

:deep(.el-tag--default) {
  margin-left: 8px;
}
</style>
